package sushil.luc.ticket;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import sushil.luc.dtos.OrderDTO;
import sushil.luc.dtos.TicketDTO;
import sushil.luc.gui.ScanItemFragment;
import sushil.luc.network.Callback;
import sushil.luc.network.NetworkHandler;
import sushil.luc.network.SimpleGetTask;


public class TicketService {

    
    private final String webServer = "http://sushilshilpakar.com.np/smartrfid/";
    private final String URL = webServer+"api/orders/query.php?limit=20&filters=checkedOrders";
    private static List<Ticket> Truckertickets;
    
   // private final boolean UseStaticData=true;


	public TicketService()
	{
		if (Truckertickets!=null)
		{
			// DO nothing
		}
		else
		{
            Truckertickets = new ArrayList<Ticket>();
		}
	}
	
	/**
	 * Checks if the resulting Ticket from the DTO file is already contained in the TruckerTicketList
	 * @param myTicketDTO
	 * @return true if the Ticket already exists, false if not
	 */
    public boolean doesTicketExist(TicketDTO myTicketDTO) {
        boolean ticketExists = false;
        for(Ticket ticket : Truckertickets) {
            if(ticket.getId()==myTicketDTO.getId()){
                ticketExists = true;
                break;
            }
        }
        return ticketExists;
    }
    
    /**
     * Sets all the Items from the Ticket to picked up
     * @return false if there was a problem, true if everything was fine
     */
    public void ticketStaged (Ticket t)
    {
    	SimpleGetTask getTask = new SimpleGetTask(t, SimpleGetTask.TicketStaged);
    	getTask.execute();
    	
    }
    
    public List<Ticket> fetchTruckerTickets(final Context context) 
    {
    	Log.i("TS:", "Fetching tickets");
        
	        final int limit = 5;
	        
	        if (Truckertickets.size()< limit)
	        {	
		        final NetworkHandler networkHandler = NetworkHandler.getInstance();
		        networkHandler.setContext(context);
		

		        // First get order then get ticket by id
		        final List<OrderDTO> orderDTOList = new ArrayList<OrderDTO>();
		
		        try {
		            networkHandler.readList(URL,OrderDTO[].class, new Callback<List<OrderDTO>>() {
		                @Override
		                public void callback(final List<OrderDTO> myOrderDTOList) {
		                    Log.i("TS:", "size of orders = "+myOrderDTOList.size());
		                    orderDTOList.addAll(myOrderDTOList);
		
		                    for(final OrderDTO orderDto:orderDTOList) {
		                        String ticketsUrl = webServer+"api/tickets/query.php?identifiers="+orderDto.getIdentifier(); //identifier id dticketid
		                        Log.d("TS",ticketsUrl);
		                        //String ticketsUrl = "http://192.168.2.69/smartrfid/api/ticket.json";
		                        try {
		                            networkHandler.read(ticketsUrl,TicketDTO.class, new Callback<TicketDTO>() {
		                                @Override
		                                public void callback(final TicketDTO myTicketDTO) {
		                                	if (myTicketDTO.getItems()!=null)
		                                		Log.i("TS:", "size of items in ticket = "+myTicketDTO.getItems().size());
		                                    //ticketDTOList.add(myTicketDTO);
		                                    // map each orderdto,ticketdto to Tickets model
                                            Log.d("TS ","C "+orderDto.getStatus().isCheckedOut());
                                            Log.d("TS", "check "+(!doesTicketExist(myTicketDTO)));
		                                    if((!doesTicketExist(myTicketDTO)) && orderDto.getStatus().isCheckedOut()==1) {
		                                    	Truckertickets.add(new Ticket(myTicketDTO, orderDto));
                                                ScanItemFragment.updateTicketList();
		                                    }
		                                }
		                            });
		                            
		                        } catch (Exception e) {
                                    e.printStackTrace();
		                            Toast.makeText(context, "Could not connect. Please check your connection.", Toast.LENGTH_LONG).show();
		                        }
		                    }

		                }
		            });
		           
		        } catch (Exception e) {
                    e.printStackTrace();
		            Toast.makeText(context, "Could not connect. Please check your connection.", Toast.LENGTH_LONG).show();
		        }
	        }
      
        return Truckertickets;
    }
    
    public List<Ticket> getLocalTruckerTickets()
    {
    	return Truckertickets;
    }
    
    
    public void updateTicketStaged(Ticket t)
    {
    	SimpleGetTask getTask = new SimpleGetTask(t, SimpleGetTask.TicketStaged);
    	getTask.execute();
    }
}
